package manageAbilitiesServlets;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.requestAbilitySession.RequestAbilitySessionRemote;

public class RequestAbilityServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertAbilityRequest(request, response);
		try {
			response.sendRedirect("/ProgettoWeb/ManageAbilitiesForUser.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertAbilityRequest(request, response);
		try {
			response.sendRedirect("/ProgettoWeb/ManageAbilitiesForUser.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void insertAbilityRequest(HttpServletRequest request,
			HttpServletResponse response) {
		Calendar now = Calendar.getInstance();
		Date date = now.getTime();
		try {
			Context jndiCtx = new InitialContext();
			RequestAbilitySessionRemote requestAbilitySession = (RequestAbilitySessionRemote) jndiCtx
					.lookup("Progetto/RequestAbilitySession/remote");

			int idUser, idAbility;
			idUser = (Integer) request.getSession().getAttribute("id");
			if (request.getParameter("name") != null) {
				idAbility = Integer.parseInt((String) request
						.getParameter("name"));

				if (requestAbilitySession.insertAbilityRequest(idUser,
						idAbility, date) != 0)
					// richiesta inserita correttamente
					request.getSession().setAttribute("result", "requested");
				else
					request.getSession().setAttribute("result", "mistake");
			}else
				request.getSession().setAttribute("result", "mistake");
		} catch (NamingException e) {
			System.out.print("errore nella connessione remota");
			e.printStackTrace();
			request.getSession().setAttribute("result", "mistake");
		}
	}

}
